package com.shujia.flink.window;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

/**
 * @author shujia
 */
public class Demo6EventTimeSessionWindow {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStream<String> lines = env.socketTextStream("master", 8888);

        /*
java,1686966529000
java,1686966530000
java,1686966537000
java,1686966540000
         */
        //解析数据，取出时间字段
        DataStream<Tuple2<String, Long>> wordAndTs = lines.map(line -> {
            String[] split = line.split(",");
            String word = split[0];
            long ts = Long.parseLong(split[1]);
            return Tuple2.of(word, ts);
        }, Types.TUPLE(Types.STRING, Types.LONG));


        WatermarkStrategy<Tuple2<String, Long>> watermarkStrategy = WatermarkStrategy
                //水位线生产策略
                .<Tuple2<String, Long>>forMonotonousTimestamps()
                //知道时间字段
                .withTimestampAssigner((event, ts) -> event.f1);

        //指定时间字段和水位线
        DataStream<Tuple2<String, Long>> ass = wordAndTs.assignTimestampsAndWatermarks(watermarkStrategy);

        //转换成kv格式
        DataStream<Tuple2<String, Integer>> kvs = ass.map(word -> Tuple2.of(word.f0, 1), Types.TUPLE(Types.STRING, Types.INT));

        KeyedStream<Tuple2<String, Integer>, String> keyBy = kvs.keyBy(kv -> kv.f0);


        /*
         * 会话窗口,一段时间没有数据生成一个窗口
         * EventTimeSessionWindows:事件时间的会话窗口, 当新的数据过来,时间间隔超过5秒开始计算
         * ProcessingTimeSessionWindows:处理时间的会话窗口
         */

        WindowedStream<Tuple2<String, Integer>, String, TimeWindow> windows = keyBy
                //如果5秒没有数据计算一次
                .window(EventTimeSessionWindows.withGap(Time.seconds(5)));

        windows.sum(1)
                .print();


        env.execute();

    }
}
